package com.cs.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.cs.spzx.exception.GuiguException;
import com.cs.spzx.manager.mapper.SysUserMapper;
import com.cs.spzx.manager.service.SysUserService;
import com.cs.spzx.model.dto.system.LoginDto;
import com.cs.spzx.model.entity.system.SysUser;
import com.cs.spzx.model.vo.common.ResultCodeEnum;
import com.cs.spzx.model.vo.system.LoginVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate<String,String> redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();//序列化为String
        //不能反序列化
        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(serializer);
        this.redisTemplate = redisTemplate;
    }

    @Override
    public LoginVo login(LoginDto loginDto) {

            // 校验验证码是否正确
            String captcha = loginDto.getCaptcha();     // 用户输入的验证码
            String codeKey = loginDto.getCodeKey();     // redis中验证码的数据key

            // 从Redis中获取验证码
            String redisCode = redisTemplate.opsForValue().get("user:login:validatecode:" + codeKey);
            if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode , captcha)) {
                throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR) ;
            }
            // 验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validatecode:" + codeKey) ;
        //1.通过用户名查询用户信息
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());
        if(sysUser == null){
            throw new RuntimeException("用户名或者密码错误");
        }
        //2.验证密码是否正确
        String inputPassword = loginDto.getPassword();
        String md5InputPassword = DigestUtils.md5DigestAsHex(inputPassword.getBytes());
        if(!md5InputPassword.equals(sysUser.getPassword())){
            throw new RuntimeException("用户名或者密码错误");
        }

        //3.生成令牌(token)，并保存数据到redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser), 30, TimeUnit.MINUTES);

        //4.构建结果对象并返回
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        return JSON.parseObject(userJson , SysUser.class) ;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token) ;
    }

    public static void main(String[] args) {
        String token = UUID.randomUUID().toString().replace("-", "");
        System.out.println(token);
    }
}
